package com.hippy.erya.modular.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.hippy.erya.exception.EyErrorCode;
import com.hippy.erya.exception.EyException;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EasyPoiExportUtil {


    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }


    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }

    public static void exportExcelList(List<List<?>> list, List<String> titles, List<String> sheetNames, List<Class<?>> pojoClassList, String fileName, HttpServletResponse response){
        List<Map<String, Object>> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> sheet = new HashMap<>();
            sheet.put("title", new ExportParams(titles.get(i),sheetNames.get(i)));
            sheet.put("entity", pojoClassList.get(i));
            sheet.put("data",list.get(i));
            lists.add(sheet);
        }

        Workbook workbook = ExcelExportUtil.exportExcel(lists, ExcelType.HSSF);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }


    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel");
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            throw new EyException(EyErrorCode.EXPORT_IS_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }
}
